import Vue from 'vue'
import Router from 'vue-router'
import store from '../store/store'

const Login = () => import('@/components/Login');
const UserInfo = () => import('@/components/UserInfo');
const Register = () => import('@/components/Register');
const Reset = () => import('@/components/ResetPassword');
const userdetails = () => import('@/view/userdetails');
const analysisDes = () => import('@/view/analysisDes');
const pricedetails = () => import('@/view/pricedetails');


Vue.use(Router)
const router = new Router({
  routes: [
    { path: '/', redirect: "/login" },
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    { path: '/reset', component: Reset },
    { path: '/userinfo', name: "userinfo", component: UserInfo },
    // 天探设备管理
    { path: "/userdetails", name: 'userdetails', component: userdetails },//用户基本信息详情
    { path: "/analysisDes", component: analysisDes },//用户体检信息详情
    { path: "/pricedetails", name: "pricedetails", component: pricedetails },//天探设备信息详情
    { path: '/days', component: resolve => (require(['@/view/days'], resolve)) },
    { path: "*", redirect: "/login/:id" }
  ]
})
// 注册全局钩子用来拦截导航
router.beforeEach((to, from, next) => {
  const token = store.state.Authorization
  if (to.path != "/login") { // 判断该路由
    if (token) { // 通过vuex state获取当前的token是否存在
      next()
    } else {
      store.commit("clear");
      localStorage.clear();
      next({
        path: '/login',
        // query: {redirect: to.index} // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  } else {
    next()
  }
})
router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  const targetPath = router.history.pending.fullPath;
  if (isChunkLoadFailed) {
    router.replace(targetPath);
  }
});
export default router;